import router from '@/credit/router'
import { getData, getDataFromId } from '@vimi/utils-api'

const state = {
  accountInfo: {},
  farmInfo: {},
  farmId: '',
  accountId: '',
  configId: '',
  farmSubject: [],
  subjectTree: [],
  subjectTreeLast: [],
  subjectTreeAll: [],
  subjectProfit: {}, // 年盈余科目，不可修改
  configInfo: {},
}

// this.$store.getters.
const getters = {
  accountInfo: state => state.accountInfo,
  farmInfo: state => state.farmInfo,
  farmId: state => state.farmId,
  accountId: state => state.accountId,
  configId: state => state.configId,
  farmSubject: state => state.farmSubject,
  subjectTree: state => state.subjectTree,
  subjectTreeLast: state => state.subjectTreeLast,
  subjectTreeAll: state => state.subjectTreeAll,
  subjectProfit: state => state.subjectProfit,
  configInfo: state => state.configInfo,
}

// this.$store.dispatch('...')
const actions = {
  async getFarmInfo({ commit }) {
    let farmId = router.currentRoute.query.id || localStorage.getItem('accountId')
    if (!farmId) return
    commit('farmId', farmId)
    try {
      let r = await getData(
        'account',
        'service_farm_list_accountant_view',
        {
          index: 1,
          size: 1,
          farm_id: farmId,
        },
        {
          farm_id: 'eq',
        }
      )
      if (r.data.data && r.data.data.length) {
        commit('farmInfo', r.data.data[0])
        commit('accountId', r.data.data[0].id)
        this.dispatch('getAccountInfo')
      }
    } catch (err) {
      router.replace('/summary')
    }
  },
  async getAccountInfo({ commit }) {
    try {
      let res = await getDataFromId('account', 'service_farm_list', state.accountId)
      commit('accountInfo', res.data)
      commit('configId', res.data.config_id)
      this.dispatch('getAccountSubject')
      this.dispatch('getAccountConfig')
    } catch (err) {
      router.replace('/summary')
    }
  },
  async getAccountSubject({ commit }) {
    let farmId = state.farmId
    if (!farmId) return
    let res = await getData(
      'account',
      'farm_subject_view',
      {
        farm_id: farmId,
      },
      {
        farm_id: 'eq',
      }
    )
    if (res.data) {
      commit(
        'farmSubject',
        res.data.map(item => {
          item.option = `${item.subject_key} ${item.subject_value}`
          return item
        })
      )
    } else {
      commit('farmSubject', [])
    }
    this.dispatch('getSubjectTree')
  },
  async getAccountConfig({ commit }) {
    let configId = state.configId
    if (!configId) return
    let res = await getDataFromId('account', 'account_config', configId)
    commit('configInfo', res.data || {})
    this.dispatch('getSubjectTree')
  },
  getSubjectTree({ commit }) {
    let st = state.configInfo.subject_structure
    let fs = state.farmSubject
    // 科目结构 [3, 5, 7]
    let ss = st ? st.split('-') : []
    let structure = []
    let sum = 0
    for (let s of ss) {
      sum += +s
      structure.push(sum)
    }

    let getLevel = key => {
      if (!key) return 0
      let _level = 0
      let _len = `${key}`.length
      for (let v of structure) {
        if (_len === v) return _level
        _level++
      }
      return 0
    }

    // 存各级数据的空数组 [[],[]]
    let arr = []
    let len = structure.length
    for (let i = 0; i < len; i++) {
      arr.push([])
    }
    // 存入数据 [[一级科目列表],[二级科目列表]]
    // tree的数据结构只要一级科目列表，下级科目全部归入children中
    for (let s of fs) {
      let l = getLevel(s.subject_key)
      if (l < len) {
        let data = {}
        Object.keys(s).forEach(key => {
          data[key] = s[key]
        })
        data.id = s.subject_key
        data.label = s.subject_value
        data.option = `${s.subject_key} ${s.subject_value}`
        arr[l].push(data)
      }
      if (s.knots_type === '1') {
        commit('subjectProfit', s)
      }
    }

    // 一级一级的赋值children，从后往前，第一级不用操作
    for (let i = arr.length - 1; i > 0; i--) {
      const cf = arr[i - 1]
      for (const d of arr[i]) {
        const val = d.id ? d.id.substring(0, structure[i - 1]) : ''
        const index = cf.findIndex(it => it.id === val)
        if (index > -1) {
          d.parent_subject_key = cf[index].subject_key
          d.parent_subject_value = cf[index].subject_value
          if (cf[index].children) {
            cf[index].children.push(d)
          } else {
            cf[index].children = [d]
          }
        }
      }
    }

    let res = arr.length ? arr[0] : []
    commit('subjectTree', res)

    // 所有列表
    let allList = []
    for (let k = arr.length - 1; k >= 0; k--) {
      for (let d of arr[k]) {
        allList.push(d)
      }
    }
    commit('subjectTreeAll', allList)

    // 只取最后一级，递归多级科目列表取最后一级
    let resLast = []
    let findLast = arr => {
      if (arr) {
        for (let a of arr) {
          if (a.children) {
            findLast(a.children)
          } else {
            resLast.push(a)
          }
        }
      }
    }
    findLast(res)
    commit('subjectTreeLast', resLast)
  },
}

// this.$store.commit('...', value)
const mutations = {
  accountInfo: (state, payload) => {
    state.accountInfo = payload
  },
  farmInfo: (state, payload) => {
    state.farmInfo = payload
  },
  farmId: (state, payload) => {
    state.farmId = payload
  },
  accountId: (state, payload) => {
    state.accountId = payload
  },
  configId: (state, payload) => {
    state.configId = payload
  },
  farmSubject: (state, payload) => {
    state.farmSubject = payload
  },
  subjectTree: (state, payload) => {
    state.subjectTree = payload
  },
  subjectTreeLast: (state, payload) => {
    state.subjectTreeLast = payload
  },
  subjectTreeAll: (state, payload) => {
    state.subjectTreeAll = payload
  },
  subjectProfit: (state, payload) => {
    state.subjectProfit = payload
  },
  configInfo: (state, payload) => {
    state.configInfo = payload
  },
}

export default {
  state,
  getters,
  actions,
  mutations,
}
